package backend;
import java.io.BufferedReader;

import java.io.IOException;

/*
 * Parse the level file for Pipe Dream Solver. Verifies the file satisfies the requirements
 * to have a correct level. 
 * First line should have 2 numbers separated by a comma indicating the size of the map.
 * Then, as many lines as the first number of the first line which indicates the rows
 * of the map.
 * Each line should have as many characters as the second number of the first line,
 * which indicates the columns of the map. A "#" indicates a wall, a blank indicates
 * nothing in that position. Also N,S,W,E to indicate the start direction of the water
 * in the position of the letter. Only one is admitted.
 * Last 7 lines indicate the number of pipes for each one in order:
 * WN - EN - ES - WS - NS - WE - CROSS
 */
public class Parser {
	public static void Parseo(BufferedReader In,PDreamSolver game) throws IOException, ParserException{			 
		int rows;
		int cols;
		int starts=0;
		String linea=In.readLine();
		linea=linea.trim();

		if(linea==null){
			throw new ParserException();
		}
		else{
			int coma=linea.indexOf(',');
			if(coma == -1){
				throw new ParserException();
			}
			String row=linea.substring(0, coma);
			if(coma == linea.length()){
				throw new ParserException();
			}
			String col=linea.substring(coma+1).trim();
			rows=new Integer(row);
			cols=new Integer(col);
			game.setDim(new Position(rows,cols));
		}
		for(int i=0;i<rows;i++){
			linea=In.readLine();
			for(int j=0;j<cols;j++){
				char c=linea.charAt(j);
				switch (c){
				case '#':
					game.add(new Position(j,i),new Wall());
					break;
				case 'N': 
					game.setStart(InputTypes.N,new Position(j,i));
					starts++;
					break;
				case 'E': 
					game.setStart(InputTypes.E,new Position(j,i));
					starts++;
					break;
				case 'S': 
					game.setStart(InputTypes.S,new Position(j,i));
					starts++;
					break;
				case 'W': 
					game.setStart(InputTypes.W,new Position(j,i));
					starts++;
					break;
				case ' ': 
					break;
				default: 
					throw new ParserException();
				}
				if(starts>1){
					throw new ParserException();
				}
			}
		}
		if(starts!=1){
			throw new ParserException();
		}

		for(int i=0;i<7;i++){
			try{
				linea=In.readLine();
				linea=linea.trim();
				int cant=new Integer(linea);
				game.setTube(cant,i);
			}
			catch (Exception e){
				throw new ParserException();
			}
		}
		if(In.readLine()!=null){
			throw new ParserException();
		}
	}
}
